package com.kandinfo.base.security.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kandinfo.base.common.dto.ResultDto;
import com.kandinfo.base.common.dto.ResultDtoFactory;
import com.kandinfo.base.security.SecurityContext;
import com.kandinfo.base.security.domain.Permission;
import com.kandinfo.base.security.domain.Role;
import com.kandinfo.base.security.domain.RolePermission;
import com.kandinfo.base.security.domain.User;
import com.kandinfo.base.security.dto.PermissionDto;
import com.kandinfo.base.security.dto.RolePermissionPostDto;
import com.kandinfo.base.security.repository.PermissionRepository;
import com.kandinfo.base.security.repository.RolePermissionRepository;
import com.kandinfo.base.security.repository.RoleRepository;


@Controller
public class PermissionController {
    @Autowired
    SecurityContext securityContext;

    @Autowired
    RoleRepository roleRepository;

    @Autowired
    RolePermissionRepository rolePermissionRepository;

    @Autowired
    PermissionRepository permissionRepository;

    
    // 页面：权限管理
    @RequestMapping(value = "/permission", method = RequestMethod.GET)
    public String permissionManeger(Model model) {
        List<PermissionDto> list=new ArrayList<PermissionDto>();
        List<Role> rolesExceptAdmin = roleRepository.findRoleNotAdmin();
        model.addAttribute("rolesExceptAdmin", rolesExceptAdmin);
        List<Permission> orignPermissions=permissionRepository.findorignPermissions();
        for(Permission perm:orignPermissions){
            PermissionDto dto =new PermissionDto();
            dto.setPermission(perm);
            List<Permission> childList=permissionRepository.findChildPermissions(perm.getId());
            dto.setPermissionList(childList);
            list.add(dto);
        }
        model.addAttribute("list", list);
        return "sys/permission_list";
    }
    
    
    
    // 求情数据：获取角色的权限
    @RequestMapping(value = "/system/getRolePermissions", method = RequestMethod.GET)
    @ResponseBody
    public ResultDto getRolePermissions(
            @RequestParam(value = "roleId") String roleIdString) {
        Long roleId = Long.valueOf(roleIdString);
        List<RolePermission> rolePermissions = rolePermissionRepository
                .findByRoleId(roleId);
        if (rolePermissions == null || rolePermissions.size() == 0) {
            return ResultDtoFactory.toAckNomessage("查询成功", null);
        } else {
            return ResultDtoFactory.toAckNomessage("查询成功", rolePermissions);
        }
    }

    // 提交数据
    // assignPermissions
    @RequestMapping(value = "/system/assignPermissions", method = RequestMethod.POST)
    @ResponseBody
   // @RequiresPermissions(value = Permissions.ADMIN_PERMISSION_MANAGE)
    public ResultDto assignPermissions(
            @RequestBody RolePermissionPostDto rolePermissionPostDto,
            HttpServletRequest request) {
        Long  roleId = Long.parseLong(rolePermissionPostDto.getRoleId().trim());
        String[] permissions = rolePermissionPostDto.getPermissions()
                .split(",");
        int permissionsLength = permissions == null ? 0 : permissions.length;
        User loginUser = securityContext.getCurrentUser();
        List<RolePermission> originalRolePermissions = rolePermissionRepository
                .findByRoleId(roleId);
        if (originalRolePermissions != null
                && originalRolePermissions.isEmpty()) {
            rolePermissionRepository.delete(originalRolePermissions);
        }
        int count = permissionsLength;
        if (permissionsLength > 0) {
            for (int i = 0; i < permissions.length; i++) {
                RolePermission temp = new RolePermission();
                temp.setRoleId(Long.valueOf(roleId));
                temp.setPermId(Long.valueOf((permissions[i].trim())));
                temp.setCreateTs(new Date());
                temp.setCreateBy(loginUser.getId());

                RolePermission saved = rolePermissionRepository.save(temp);
                if (saved != null) {
                    count--;
                }
            }
        }
        if (count == 0) {
            return ResultDtoFactory.toAck("保存成功", null);
        } else {
            // 回滚数据
            List<RolePermission> nowRolePermissions = rolePermissionRepository
                    .findByRoleId(roleId);
            if (nowRolePermissions != null && nowRolePermissions.isEmpty()) {
                rolePermissionRepository.delete(nowRolePermissions);
            }

            for (RolePermission item : originalRolePermissions) {
                RolePermission temp = new RolePermission();
                temp.setRoleId(item.getRoleId());
                temp.setPermId(item.getPermId());
                temp.setCreateTs(item.getCreateTs());
                temp.setCreateBy(item.getCreateBy());

                rolePermissionRepository.save(temp);
            }
            return ResultDtoFactory.toNack("保存失败", null);
        }
    }
}
